import axios from 'axios'
import { ElMessage } from 'element-plus'
import { diffTokenTime } from '@/utils/auth'
import store from '@/store'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 基础路径
  timeout: 5000 // 超时时间
})

service.interceptors.request.use(config => {
  // 如果有token就判断token是否过期
  if (localStorage.getItem('token')) {
    if (diffTokenTime()) {
      store.dispatch('app/logout')
      return Promise.reject(new Error('token 失效了'))
    }
  }

  config.headers.Authorization = localStorage.getItem('token')
  return config
}, error => {
  return error.Promise.reject(new Error(error))
})

service.interceptors.response.use((response) => {
  const { data, meta } = response.data
  // 请求响应
  if (meta.status === 200 || meta.status === 201) {
    return data
  } else {
    ElMessage.error(meta.msg)
    return Promise.reject(new Error(meta.msg))
  }
}, error => {
  error.response && ElMessage.error(error.response.data)
  return Promise.reject(new Error(error.response.data))
})

export default service
